// pages/throw/throw.js
Page({
  data: {
    types: [
      { id: 1, name: '公开瓶' },
      { id: 2, name: '爱情瓶' },
      { id: 3, name: '交友瓶' },
      { id: 4, name: '匿名瓶' }
    ],
    type: 1, // 默认选择公开瓶
    content: '',
    isSubmitting: false,
    showSuccessTip: false,
    typeIndex: 0 // 用于 picker 组件
  },

  onLoad: function (options) {
    this.setData({
      typeIndex: 0,
      type: this.data.types[0].id
    });
  },

  // 类型选择器变更
  onTypeChange: function (e) {
    const index = e.detail.value;
    this.setData({
      typeIndex: index,
      type: this.data.types[index].id
    });
  },

  // 内容输入
  onContentInput: function (e) {
    this.setData({ content: e.detail.value });
  },

  // 字数统计
  onContentChange: function (e) {
    const content = e.detail.value;
    this.setData({ content });
  },

  // 提交表单
  onSubmit: function () {
    const { content, isSubmitting, type, types } = this.data;
    // 检查内容是否为空
    if (!content.trim()) {
      wx.showToast({
        title: '内容不能为空',
        icon: 'none'
      });
      return;
    }
    // 检查内容长度
    if (content.length > 300) {
      wx.showToast({
        title: '内容不能超过300字',
        icon: 'none'
      });
      return;
    }
    if (isSubmitting) return;
    this.setData({ isSubmitting: true });
    // 调用云函数
    wx.cloud.callFunction({
      name: 'throwBottle',
      data: {
        type,
        typeName: types.find(item => item.id === type).name,
        content,
        openid: wx.getStorageSync('openid') || '' // 建议用云开发 openid，演示用本地
      },
      success: res => {
        if (res.result && res.result.code === 0) {
          this.setData({
            isSubmitting: false,
            showSuccessTip: true
          });
        } else {
          wx.showToast({ title: res.result.msg || '提交失败', icon: 'none' });
          this.setData({ isSubmitting: false });
        }
      },
      fail: err => {
        wx.showToast({ title: '网络错误', icon: 'none' });
        this.setData({ isSubmitting: false });
      }
    });
  },

  // 格式化时间
  formatTime: function (date) {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();

    return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
  },

  // 返回列表
  backToList: function () {
    wx.navigateBack();
  },

  // 继续扔瓶子
  continueThrowing: function () {
    this.setData({
      showSuccessTip: false,
      content: ''
    });
  }
});    